<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>上传图片</title>
    <style>
        /* #pg{
            display: inline-block;
            width: 150px;
            height: 10px;
            border-radius: 5px;
            border: 1px solid #ccc;
        } */
    </style>
    <script src="jquery1.9/jquery-1.9.0.min.js"></script>
    <script>
        function doUpload(){
            let f=document.getElementById("f").files[0];
            console.log(f);
            var formData=new FormData();
            formData.append("headImage",f);

            var xhr=new XMLHttpRequest();
            xhr.onload=function(){
                if(xhr.status==200){
                    console.log(xhr.responseText);
                    document.getElementById("m").src=xhr.responseText;
                }
            }

             // 监听文件上传的进度, 会周期性的回调此函数
            xhr.upload.onprogress=function(event){
                if(event.lengthComputable){
                    let percent=Math.ceil(event.loaded*100/event.total);
                    document.getElementById("pg").value=percent;

                    // document.getElementById("pg").innerText=percent;
                    // for(var i=0;i<=percent;i++){
                    //     var span=$(`<span style="background:yellow;">${percent}%</span>`);
                    //     $("#pg").append(span);
                    // }

                    document.getElementById("showPg").innerText=percent + "%";
                }
            }

            xhr.open("post","./service/upload.php");
            xhr.send(formData);

        }
    </script>
</head>
<body>
    <form id="form">
        <div>
            <label>
                文件: <input id="f" type="file" name="headImage">
                <progress id="pg" max="100" value="0" ></progress>
                <!-- 新建进度条 -->
                <!-- <span id="pg"></span> -->
                <span id="showPg">0%</span>
            </label>
        </div>
        <div>
            <input type="button" value="上传" onclick="doUpload()" />
        </div>
    </form>
    <hr>
    <h3>预览:</h3>
    <img id="m" src="" style="width: 200px;"  alt="no image">
</body>
</html>